import axios from 'axios'
import { Toast } from 'vant';
import qs from 'qs';
import router from '@/router/index'

const service = axios.create({
	baseURL: process.env.VUE_APP_URL, // url = base url + request url
	withCredentials: true, // send cookies when cross-domain requests
	timeout: 5000000 // request timeout
})

service.interceptors.request.use(
	config => {
		return config;
	}, error => {
		return Promise.reject(error);
	}
)
// response interceptor
service.interceptors.response.use(
	response => {
		const res = response.data;
		if (res.result == 0) {
			Toast('请先登录');
			return Promise.reject(new Error(res.errorMessage || 'Error'))// return new Promise(() => {})
		}
		if (res.result == 0 || res.result == "sessionout" || res.result == "sessionexpired" || res.result=="sessionmore") {
			router.replace({path: "/"});
			return Promise.reject(new Error(res.errorMessage || 'Error'))// return new Promise(() => {})
		}
		if(response.data.code == 403){
			window.location.href=process.env.VUE_APP_URL + 'error/403';
		}
		var re=res.desc || res.data || res;
		if(typeof re=="string"){
			router.replace({path: "/"});
			return false;
		}
		return re;
	},
	error => { //http不是200
		if(error.response.status=="403"){
			Toast('您没有权限访问该资源');
		}
		else{
			Toast('服务器忙，请稍后访问');
		}
		if (axios.isCancel(error)) { 
		    return new Promise(() => {})
		} 
		return Promise.reject(error)
	}
)
export default service
